#import hashlib   
import cgi
import wsgiref.handlers
import os

from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp import template

class QW_GsScore(db.Model):
    id = db.StringProperty()
    score = db.IntegerProperty()
    snsFlag = db.IntegerProperty();
    date = db.DateTimeProperty(auto_now_add=True)
    
class QW_sns():
    snsArr = ['x','5','m','t','k']
    def getId(self, name=None):
        for i in range(len(self.snsArr)):
            if self.snsArr[i] == name:
                return i
        return -1
    def getWebSiteAbb(self, id=None):
        if id > -1 and id < len(self.snsArr):
            return self.snsArr[id]

class QW_getScore(webapp.RequestHandler):
    def get(self):
        idReceived = self.request.get('id')
        scoreStr = self.request.get('score')
        snsFlag = self.request.get('snsFlag')
        if idReceived and scoreStr and snsFlag:
            scoreInt = int(scoreStr)
            snsFlag = QW_sns().getId(snsFlag)
            if scoreStr >0 and snsFlag != -1:
                gsScore = QW_GsScore()
                gsScore.id = idReceived
                gsScore.score = scoreInt
                gsScore.snsFlag = snsFlag
                gsScore.put()
                totalPlayerNum = QW_GsScore.all().count(1000)
                rankOfMe = QW_GsScore.all().filter('score >', scoreInt).count(1000)
                output = '1@#@' + str(totalPlayerNum) + '@#@' + str(rankOfMe + 1)
                self.response.out.write(output)
            else :
                self.response.out.write('0@#@0@#@0')
        else:
            self.redirect('/top10')
#            score_query = QW_GsScore.all().order('-score')
#            scores = score_query.fetch(10)
#            template_values = {'scores' : scores,}
#            path = os.path.join(os.path.dirname(__file__), '../template/index.html')
#            self.response.out.write(template.render(path, template_values))
    def post(self):
        self.get()

def main():
  application = webapp.WSGIApplication(
                                       [('/', QW_getScore)],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()